/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.common.xml;


import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;

/**
 * XMLStreamReader reader = getStreamReader((Reader) null);
 * while(reader.hasNext()) {
 * int next = reader.next();
 * reader.getName();
 * }
 *
 * @author: vacoor
 */
public abstract class StAX {

    public static XMLStreamReader getStreamReader(String xml) throws XMLStreamException {
        return getStreamReader(new StringReader(xml));
    }

    public static XMLStreamReader getStreamReader(InputStream is) throws XMLStreamException {
        return getInputFactory().createXMLStreamReader(is);
    }

    public static XMLStreamReader getStreamReader(Reader reader) throws XMLStreamException {
        return getInputFactory().createXMLStreamReader(reader);
    }

    public static XMLStreamReader getStreamReader(Source source) throws XMLStreamException {
        return getInputFactory().createXMLStreamReader(source);
    }

    public static XMLInputFactory getInputFactory() {
        XMLInputFactory factory = XMLInputFactory.newInstance();

        factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        //IS_COALESCING property to true
        //gets whole text data as one event
        factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);

        return factory;
    }
}
